from sqlmodel import select
from sqlalchemy.orm import joinedload
from app import  models,crud
from typing import Optional
from app.core.security import get_password_hash
from fastapi import status
from .base import BaseService
from app.utils import generate_verification_code,send_sms
from datetime import datetime,timedelta
class AreaService(BaseService):  
    async def get_areas(self) -> models.areasPublic:
        # 一次性查询所有地区数据
        stmt = select(models.Area).order_by(models.Area.sort)
        areas = self.db.execute(stmt)
        areas = areas.scalars().all()
        
        # 将子地区按父级代码分组
        children_map = {}
        parent_areas = []
        
        for area in areas:
            if area.parentCode is None:
                parent_areas.append(area)
            else:
                if area.parentCode not in children_map:
                    children_map[area.parentCode] = []
                children_map[area.parentCode].append(area)
        
        # 构建树形结构
        result = []
        for parent in parent_areas:
            children = children_map.get(parent.regionCode, [])
            parent_node = models.areaPublic(
                value=parent.regionCode,
                text=parent.regionName,
                children=[
                    models.areaChildPublic(
                        value=child.regionCode,
                        text=child.regionName
                    ) for child in children
                ]
            )
            result.append(parent_node)
            
        return models.areasPublic(code=0,msg="成功",data=result)

        